//
//  GYCartConfirmVC.m
//  GYDemo
//
//  Created by mac on 2018/4/8.
//  Copyright © 2018年 mac. All rights reserved.
//

//
//                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
//            __.'              ~.   .~              `.__
//          .'//                  \./                  \\`.
//        .'//                     |                     \\`.
//      .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-. \\`.
//    .'//.-"                 `-.  |  .-'                 "-.\\`.
//  .'//______.============-..   \ | /   ..-============.______\\`.
//.'______________________________\|/______________________________`.
//
//

#import "GYCartConfirmVC.h"
#import "Head.h"
#import "GYMineShopAddressVC.h"
@interface GYCartConfirmVC ()
@property (nonatomic,strong) UIView *confirmV;
@property (nonatomic,strong) UILabel *finalPriceLB;
@property (nonatomic,strong) UILabel *serverPriceLB;
@property (nonatomic,strong) UIButton *confirmBtn;
@property (nonatomic,strong) GYCartConfirmAddressView *tableHead;
@end

@implementation GYCartConfirmVC
#pragma mark - getter and setter
-(GYCartConfirmViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [GYCartConfirmViewModel new];
    }
    return _viewModel;
}
-(UIView *)confirmV
{
    if (!_confirmV) {
        _confirmV = [UIView new];
        _confirmV.width = self.view.width;
        _confirmV.height = WFCGFloatY(50);
        _confirmV.y = WF_SCREEN_HEIGHT - _confirmV.height;
        _confirmV.backgroundColor = Main_Color_White;
        [_confirmV addSubview:self.finalPriceLB];
        [_confirmV addSubview:self.serverPriceLB];
        [_confirmV addSubview:self.confirmBtn];
    }
    return _confirmV;
}

-(UILabel *)finalPriceLB
{
    if (!_finalPriceLB) {
        _finalPriceLB = [UILabel new];
        _finalPriceLB.y = WFCGFloatY(6);
        _finalPriceLB.width = WFCGFloatX(200);
        _finalPriceLB.height = WFCGFloatY(25);
        _finalPriceLB.x = self.confirmV.width - self.confirmBtn.width - WFCGFloatX(9) -_finalPriceLB.width;
        _finalPriceLB.font = SYSTEMBOLDFONT(14);
        _finalPriceLB.textAlignment = NSTextAlignmentRight;
        _finalPriceLB.textColor = HEXCOLOR(@"#FC1B36");
    }
    return _finalPriceLB;
}

-(UILabel *)serverPriceLB
{
    if (!_serverPriceLB) {
        _serverPriceLB = [UILabel new];
        _serverPriceLB.y = WFCGFloatY(29);
        _serverPriceLB.width = WFCGFloatX(200);
        _serverPriceLB.height = WFCGFloatY(14);
        _serverPriceLB.x = self.confirmV.width - self.confirmBtn.width - WFCGFloatX(9) - _serverPriceLB.width;
        _serverPriceLB.font = SYSTEMFONT(10);
        _serverPriceLB.textAlignment = NSTextAlignmentRight;
        _serverPriceLB.textColor = Main_Color_Black;
    }
    return _serverPriceLB;
}

-(UIButton *)confirmBtn
{
    if (!_confirmBtn) {
        _confirmBtn = [UIButton new];
        _confirmBtn.height = self.confirmV.height;
        _confirmBtn.width = WFCGFloatX(105);
        _confirmBtn.x = _confirmV.width - _confirmBtn.width;
        [_confirmBtn setBackgroundColor:Main_Color_Red forState:UIControlStateNormal];
        _confirmBtn.titleLabel.font = SYSTEMFONT(14);
        [_confirmBtn setTitle:@"提交订单" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:Main_Color_White forState:UIControlStateNormal];
        [_confirmBtn addTarget:self action:@selector(confirmBtnTap:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmBtn;
}
-(GYCartConfirmAddressView *)tableHead
{
    if (!_tableHead) {
        _tableHead = [GYCartConfirmAddressView new];
        @WeakSelf;
        [_tableHead addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            GYMineShopAddressVC* vc=[[GYMineShopAddressVC alloc] init];
            vc.ischoose=YES;
            vc.handler = ^(GYMineShopAddressModel *model) {
                [selfp.baseTable reloadData];
                [selfp.tableHead setModel:model];
            };
            [selfp.navigationController pushViewController:vc animated:YES];
        }];
    }
    return _tableHead;
}
#pragma mark - event
-(void)confirmBtnTap:(id)sender
{
    
    if (![WFFunctions WFStrCheckEmpty:[GYMineShopAddressViewModel shareInterface].defaultAddress.name])
    {
        
        for (int i=0; i<_passArr.count; i++) {
            GYCartShopModel* model=_passArr[i];
            NSMutableDictionary* para=[NSMutableDictionary new];
            [para setObject:model.imgpath forKey:@"imgpath"];
            [para setObject:model.name forKey:@"goodname"];
            [para setObject:[NSString stringWithFormat:@"%@",model.price] forKey:@"price"];
            [para setObject:@"1" forKey:@"num"];
            [para setObject:[NSString stringWithFormat:@"%@%@",[GYMineShopAddressViewModel shareInterface].defaultAddress.province,[GYMineShopAddressViewModel shareInterface].defaultAddress.address] forKey:@"address"];
            [para setObject:[GYMineShopAddressViewModel shareInterface].defaultAddress.name forKey:@"linkname"];
            [para setObject:[GYMineShopAddressViewModel shareInterface].defaultAddress.phone forKey:@"phone"];
            [para setObject:@"0" forKey:@"status"];
            [para setObject:[NSString stringWithFormat:@"20192030%d",[self getRandomNumber:100000 to:999999]] forKey:@"ordernum"];
            [self.viewModel requestConfirm:para];
        }
        
        

    }else
    {
        [FTIndicator showErrorWithMessage:@"请填写收货地址"];
    }
    
    
}
-(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
}
#pragma mark - method
-(void)initilization
{
    self.navigationItem.title = @"采购订单确认";
    self.extendedLayoutIncludesOpaqueBars = YES;
    
    if (@available(iOS 11.0, *)) {
        self.baseTable.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.baseTable];
    [self.view addSubview:self.confirmV];
    self.baseTable.contentInset = UIEdgeInsetsMake([self topShelterHeight], 0, [self bottomShelterHeight] + self.confirmV.height, 0);
    self.navigationController.navigationBar.shadowImage = [[UIImage new]rt_darkenWithLevel:0.3f];
    [self setNavgationTheme:1];
    self.isGroup = YES;
    [self.baseTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.baseTable setSeparatorColor: Main_Color_BG];
    [self.baseTable setBackgroundColor:Main_Color_BG];
    [self.baseTable setTintColor:Main_Color_BG];
    [self.baseTable setTableHeaderView:self.tableHead];
    
    [self viewModelBand];
    [self reloadData];
}
-(void)viewModelBand
{
    @WeakSelf;
    GCBaseObservationModel *observation = [GCBaseObservationModel new];
    observation.observation = self.viewModel;
    observation.keyPath = @"datas";
    observation.handler = ^(NSString *keyPath) {
        [selfp reloadView];
    };
    [self registObservation:observation];
    
    GCBaseObservationModel *observation2 = [GCBaseObservationModel new];
    observation2.observation = self.viewModel;
    observation2.keyPath = @"isComfired";
    observation2.handler = ^(NSString *keyPath) {
        [selfp.navigationController popViewControllerAnimated:YES];
//        GYMineBuyOrderInfoVC *buyorder = [[GYMineBuyOrderInfoVC alloc]init];
//        [[HMSNavigationController hms_getNavigationController:selfp] hms_replaceLastWithViewController:buyorder];
    };
    [self registObservation:observation2];
    
    GCBaseObservationModel *observation3 = [GCBaseObservationModel new];
    observation3.observation = [GYMineShopAddressViewModel shareInterface];
    observation3.keyPath = @"defaultAddress";
    observation3.handler = ^(NSString *keyPath) {
        [selfp reloadView];
    };
    [self registObservation:observation3];
}
-(void)reloadView
{
    [self.tableHead setModel:self.viewModel.addressModel];
   
    
    float pp=0;
    for (int i=0; i<_passArr.count; i++) {
        GYCartShopModel* model=_passArr[i];
        pp+=[model.price floatValue];
    }
     NSString *finalprices = [NSString stringWithFormat:@"%.2f元",pp];
    NSMutableAttributedString *mastr = [[NSMutableAttributedString alloc]initWithString:finalprices];
    [mastr addAttribute:NSFontAttributeName value:SYSTEMFONT(12) range:[finalprices rangeOfString:@"合计："]];
    [mastr addAttribute:NSForegroundColorAttributeName value:Main_Color_Gray range:[finalprices rangeOfString:@"合计："]];
    [mastr addAttribute:NSFontAttributeName value:SYSTEMFONT(12) range:NSMakeRange([finalprices rangeOfString:@"."].location, finalprices.length - [finalprices rangeOfString:@"."].location)];
    _finalPriceLB.attributedText = mastr;
    _serverPriceLB.text = [self.viewModel serverPrice];
    [self.baseTable reloadData];
}
-(void)reloadData
{
    [self.viewModel requestDatas];
}
-(void)inputComment:(GYCartShopModel *)model
{
    NSString *title = @"给买家留言";
    NSString *hold1 = @"请输入留言";
    TYAlertView *alertView = [TYAlertView alertViewWithTitle:title message:nil];
    [alertView addAction:[TYAlertAction actionWithTitle:@"取消" style:TYAlertActionStyleCancel handler:^(TYAlertAction *action) {
        NSLog(@"%@",action.title);
    }]];
    @WeakSelf;
    [alertView addAction:[TYAlertAction actionWithTitle:@"确定" style:TYAlertActionStyleDestructive handler:^(TYAlertAction *action) {
        UITextField *mintf = alertView.textFieldArray[0];
        if (mintf.text.length > 0) {
            NSString *min = mintf.text;
            model.comment = min;
            [selfp.baseTable reloadData];
        }else{
            [FTToastIndicator showToastMessage:@"请填写完整"];
        }
    }]];
    
    [alertView addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = hold1;
        textField.keyboardType = UIKeyboardTypeDefault;
        [textField becomeFirstResponder];
        textField.text = model.comment;
    }];
    alertView.clickedAutoHide = YES;
    TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:alertView preferredStyle:TYAlertControllerStyleAlert];
    
    //alertController.alertViewOriginY = 60;
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - life
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initilization];
    [self reloadView];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _passArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellID = @"CellID";
    GYCartConfirmGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (cell == nil) {
        cell = [[GYCartConfirmGoodsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    GYCartShopModel *chart = _passArr[indexPath.row];
    @WeakSelf;
    [cell.commentBTN addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [selfp inputComment:chart];
    }];
    cell.model = chart;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return WFCGFloatY(45);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GYCartConfirmGoodsCell *cell = (GYCartConfirmGoodsCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.height;
}

//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UIView *view = [UIView new];
//    view.width = self.view.width;
//    view.height = WFCGFloatY(39.5) + 5;
//    view.backgroundColor = Main_Color_White;
//
//    UILabel *titlelb = [UILabel new];
//    titlelb.y = 5;
//    titlelb.x = WFCGFloatX(13);
//    titlelb.width = WFCGFloatX(230);
//    titlelb.height = WFCGFloatY(39.5);
//    titlelb.font = SYSTEMFONT(15);
//    titlelb.textColor = Main_Color_Black;
//    [view addSubview:titlelb];
//
//    GYCartConfirmModel *chart = self.viewModel.datas[section];
//    titlelb.text = chart.companyname;
//
//    UIButton *phonenumbtn = [UIButton new];
//    phonenumbtn.x = WFCGFloatX(234);
//    phonenumbtn.width = WFCGFloatX(100);
//    phonenumbtn.height = WFCGFloatX(16.5);
//    phonenumbtn.centerY = view.centerY;
//    phonenumbtn.titleLabel.font = SYSTEMFONT(12);
//    [phonenumbtn setTitle:chart.mobile forState:UIControlStateNormal];
//    [phonenumbtn setTitleColor:Main_Color_Gray forState:UIControlStateNormal];
//    [phonenumbtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
//        [[GCPresenter shareInterface]phoneCall:chart.mobile];
//    }];
//    [phonenumbtn setEnlargeEdge:10];
//    [view addSubview:phonenumbtn];
//
//    UIButton *phonesign = [UIButton new];
//    phonesign.x = WFCGFloatX(340);
//    phonesign.width = WFCGFloatX(14.5);
//    phonesign.height = WFCGFloatX(14.5);
//    phonesign.centerY = view.centerY;
//    [phonesign setBackgroundImage:[UIImage imageNamed:@"phone"] forState:UIControlStateNormal];
//    //phonesign.backgroundColor = Main_Color_Blue;
//    [phonesign handleControlEvent:UIControlEventTouchUpInside withBlock:^{
//        [[GCPresenter shareInterface]phoneCall:chart.mobile];
//    }];
//    [phonesign setEnlargeEdge:10];
//    [view addSubview:phonesign];
//
//    [WFFunctions WFUIaddBorderToView:view top:NO left:NO bottom:YES right:NO borderColor:Main_Color_BG borderWidth:0.7f];
//    UIView *sep = [UIView new];
//    sep.backgroundColor = Main_Color_BG;
//    sep.width = self.view.width;
//    sep.height = 5;
//    [view addSubview:sep];
//    return view;
//}
//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return WFCGFloatX(39.5) + 5.0f;
//}

//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    UIView *view = [UIView new];
//    view.width = self.view.width;
//    view.height = WFCGFloatY(90);
//    view.backgroundColor = Main_Color_White;
//
//    GYCartConfirmModel *chart = self.viewModel.datas[section];
//
//    UILabel *statelb = [UILabel new];
//    statelb.x = WFCGFloatX(19);
//    statelb.width = WFCGFloatX(100);
//    statelb.height = WFCGFloatY(45);
//    statelb.font = SYSTEMFONT(13);
//    statelb.textColor = Main_Color_Black;
//    statelb.text = @"给卖家留言";
//    [view addSubview:statelb];
//
//    UILabel *signlb = [UILabel new];
//    signlb.x = WFCGFloatX(101);
//    signlb.width = WFCGFloatX(250);
//    signlb.height = WFCGFloatY(45);
//    signlb.font = SYSTEMFONT(13);
//    signlb.numberOfLines = 0;
//    signlb.textColor = Main_Color_Gray;
//    NSString *str = chart.comment ?: @"填写留言内容";
//    signlb.text = str;
//    [view addSubview:signlb];
//
//    CGSize temSize = [WFFunctions WFStrGetSize:str width:signlb.width font:signlb.font];
//    if (temSize.height > WFCGFloatY(45))
//    {
//        signlb.height = temSize.height;
//        statelb.height = temSize.height;
//    }
//
//    UIImageView *markIV = [[UIImageView alloc] init];
//    markIV.image = [UIImage imageNamed:@"Shape"];
//    markIV.width = markIV.image.size.width;
//    markIV.height = markIV.image.size.height;
//    markIV.x = self.view.width - WFCGFloatX(13) - markIV.width;
//    markIV.centerY = statelb.centerY;
//    [view addSubview:markIV];
//
//    UIButton *commentbtn = [UIButton new];
//    commentbtn.frame = signlb.frame;
//    @WeakSelf;
//    [commentbtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
//        [selfp inputComment:chart];
//    }];
//    [view addSubview:commentbtn];
//    //小计
//    UILabel *totallb = [UILabel new];
//    totallb.x = self.view.width - WFCGFloatX(200 + 13);
//    totallb.width = WFCGFloatX(200);
//    totallb.y = signlb.bottom;
//    totallb.height = WFCGFloatY(45);
//    totallb.font = SYSTEMBOLDFONT(14);
//    totallb.textColor = HEXCOLOR(@"#FC1B36");
//    totallb.textAlignment = NSTextAlignmentRight;
//    NSString *finalprices = [NSString stringWithFormat:@"小计：%.2f元",chart.countprice];
//    NSMutableAttributedString *mastr = [[NSMutableAttributedString alloc]initWithString:finalprices];
//    [mastr addAttribute:NSFontAttributeName value:SYSTEMFONT(12) range:[finalprices rangeOfString:@"小计："]];
//    [mastr addAttribute:NSForegroundColorAttributeName value:Main_Color_Gray range:[finalprices rangeOfString:@"小计："]];
//    [mastr addAttribute:NSFontAttributeName value:SYSTEMFONT(12) range:NSMakeRange([finalprices rangeOfString:@"."].location, finalprices.length - [finalprices rangeOfString:@"."].location)];
//    totallb.attributedText = mastr;
//    [view addSubview:totallb];
//
//    UIView *sep = [UIView new];
//    sep.width = self.view.width;
//    sep.height = 0.7f;
//    sep.backgroundColor = Main_Color_BG;
//    sep.y = statelb.bottom;
//    [view addSubview:sep];
//
//    return view;
//}
//-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    GYCartConfirmModel *chart = self.viewModel.datas[section];
//    CGSize temSize = [WFFunctions WFStrGetSize:chart.comment  width:WFCGFloatX(250) font:SYSTEMFONT(13)];
//
//    if (temSize.height > WFCGFloatY(45))
//    {
//        return WFCGFloatY(45) + temSize.height;
//    }
//    return WFCGFloatY(90);
//}
@end


/*
 11111111111111111111111111111111111111001111111111111111111111111
 11111111111111111111111111111111111100011111111111111111111111111
 11111111111111111111111111111111100001111111111111111111111111111
 11111111111111111111111111111110000111111111111111111111111111111
 11111111111111111111111111111000000111111111111111111111111111111
 11111111111111111111111111100000011110001100000000000000011111111
 11111111111111111100000000000000000000000000000000011111111111111
 11111111111111110111000000000000000000000000000011111111111111111
 11111111111111111111111000000000000000000000000000000000111111111
 11111111111111111110000000000000000000000000000000111111111111111
 11111111111111111100011100000000000000000000000000000111111111111
 11111111111111100000110000000000011000000000000000000011111111111
 11111111111111000000000000000100111100000000000001100000111111111
 11111111110000000000000000001110111110000000000000111000011111111
 11111111000000000000000000011111111100000000000000011110001111111
 11111110000000011111111111111111111100000000000000001111100111111
 11111111000001111111111111111111110000000000000000001111111111111
 11111111110111111111111111111100000000000000000000000111111111111
 11111111111111110000000000000000000000000000000000000111111111111
 11111111111111111100000000000000000000000000001100000111111111111
 11111111111111000000000000000000000000000000111100000111111111111
 11111111111000000000000000000000000000000001111110000111111111111
 11111111100000000000000000000000000000001111111110000111111111111
 11111110000000000000000000000000000000111111111110000111111111111
 11111100000000000000000001110000001111111111111110001111111111111
 11111000000000000000011111111111111111111111111110011111111111111
 11110000000000000001111111111111111100111111111111111111111111111
 11100000000000000011111111111111111111100001111111111111111111111
 11100000000001000111111111111111111111111000001111111111111111111
 11000000000001100111111111111111111111111110000000111111111111111
 11000000000000111011111111111100011111000011100000001111111111111
 11000000000000011111111111111111000111110000000000000011111111111
 11000000000000000011111111111111000000000000000000000000111111111
 11001000000000000000001111111110000000000000000000000000001111111
 11100110000000000001111111110000000000000000111000000000000111111
 11110110000000000000000000000000000000000111111111110000000011111
 11111110000000000000000000000000000000001111111111111100000001111
 11111110000010000000000000000001100000000111011111111110000001111
 11111111000111110000000000000111110000000000111111111110110000111
 11111110001111111100010000000001111100000111111111111111110000111
 11111110001111111111111110000000111111100000000111111111111000111
 11111111001111111111111111111000000111111111111111111111111100011
 11111111101111111111111111111110000111111111111111111111111001111
 11111111111111111111111111111110001111111111111111111111100111111
 11111111111111111111111111111111001111111111111111111111001111111
 11111111111111111111111111111111100111111111111111111111111111111
 11111111111111111111111111111111110111111111111111111111111111111
 
 
 */
